package com.visikard.response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.visikard.application.Constant;
import com.visikard.utility.Utils;

public abstract class BaseResponse {

	public static final int SUCCESS = 0;
	public static final int UNKNOWN_ERROR = -1;
	public static final int NETWORK_ERROR = -2;
	public static final int INVALID_RESPONSE = -3;
	public static final int USER_DEFINED_ERROR = -4;

	protected int errorCode;
	protected String errorMsg;

	public BaseResponse() {
		errorCode = SUCCESS;
		errorMsg = "";
	}

	public int getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(int errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public void extractDataFromServer(String response) throws JSONException {

		if (response != null && !response.isEmpty() && Utils.isValidJsonObject(response)) {
			JSONObject jobject = new JSONObject(response);
			String status = jobject.getString("status");
			if (status.equals(Constant.STATUS_OK)) {
				errorCode = SUCCESS;
				errorMsg = "";
			}
			else {
				String errorMsg = jobject.getString("msg");
				errorCode = UNKNOWN_ERROR;
				this.errorMsg = errorMsg;
				Log.e(Constant.TAG, "extractDataFromServer error: " + errorMsg);
			}
		}
		else {
			errorCode = BaseResponse.INVALID_RESPONSE;
			errorMsg = "Invalid response!!!";
			Log.e(Constant.TAG, "extractDataFromServer error: " + errorMsg);
		}
	}

	protected final JSONArray getDataJArray(String response) throws JSONException {
		return new JSONObject(response).getJSONArray("data");
	}

	protected final JSONObject getDataJObject(String response) throws JSONException {
		return new JSONObject(response).getJSONObject("data");
	}

}
